<template>
  <div class="container">
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/homeIndex' }">
        <i class="el-icon-s-custom"></i> 人事管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>员工信息</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <el-form :model="form" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="员工照片" required="">
            <el-upload
              action="api/employee/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              v-model="form.icon"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="员工姓名" required="">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="年龄" required="">
            <el-input v-model="form.age"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="性别" required="">
            <el-radio-group v-model="form.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="出生日期" required="">
            <el-date-picker v-model="form.birthday" type="date" placeholder="选择员工生日"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="职位" required="">
            <el-select v-model="form.postid" placeholder="请选择">
              <el-option
                v-for="postid in posts"
                :key="postid.id"
                :label="postid.name"
                :value="postid.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="部门" required="">
            <el-select v-model="form.departid" placeholder="请选择">
              <el-option
                v-for="deparid in departs"
                :key="deparid.id"
                :label="deparid.name"
                :value="deparid.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="电话号码" required="">
            <el-input v-model="form.tel"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="现住地址" required="">
            <el-cascader
              placeholder="请选择"
              v-model="form.currentAddress"
              :options="addressOptions"
              clearable
              filterable
              @change="handleAddressChange"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="详细地址" required="">
            <el-input v-model="form.address"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="政治面貌" required="">
            <el-select v-model="form.politicalid" placeholder="请选择">
              <el-option
                v-for="political in politicals"
                :key="political.id"
                :label="political.name"
                :value="political.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="婚姻状况" required="">
            <el-select v-model="form.maritalstatus" placeholder="请选择">
              <el-option
                v-for="maritalstatus in maritalstatuses"
                :key="maritalstatus.id"
                :label="maritalstatus.name"
                :value="maritalstatus.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="员工状态" required="">
            <el-select v-model="form.status" placeholder="请选择">
              <el-option
                v-for="status in statuses"
                :key="status.id"
                :label="status.name"
                :value="status.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="民族" required="">
            <el-select v-model="form.nationid" placeholder="请选择">
              <el-option
                v-for="nation in nations"
                :key="nation.id"
                :label="nation.name"
                :value="nation.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="学历" required="">
            <el-select v-model="form.education" placeholder="请选择">
              <el-option
                v-for="education in educations"
                :key="education.id"
                :label="education.name"
                :value="education.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="毕业院校" required="">
            <el-input v-model="form.school"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="入职日期" required="">
            <el-date-picker v-model="form.createTime" type="date" placeholder="选择日期"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="身份证号" required="">
            <el-input v-model="form.identity"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="员工账号" required="">
            <el-input v-model="form.account"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="备注">
            <el-input
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 10 }"
              placeholder="添加备注..."
              v-model="form.remark"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button type="primary" @click="rollback">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      id: "",
      imageUrl: "",
      form: {
        icon: "",
        name: "",
        age: "",
        gender: "",
        birthday: "",
        postid: "",
        departid: "",
        tel: "",
        currentAddress: [],
        address: "",
        politicalid: "",
        maritalstatus: "",
        status: "",
        nationid: "",
        education: "",
        school: "",
        createTime: "",
        identity: "",
        account: "",
        remark: ""
      },
      posts: [],
      departs: [],
      nations: [],
      politicals: [],
      educations: [
        { id: "0", name: "小学" },
        { id: "1", name: "初中" },
        { id: "2", name: "高中" },
        { id: "3", name: "中专" },
        { id: "4", name: "大专" },
        { id: "5", name: "本科及以上" }
      ],
      maritalstatuses: [
        { id: "0", name: "未婚" },
        { id: "1", name: "已婚" },
        { id: "2", name: "离异" },
        { id: "3", name: "丧偶" }
      ],
      statuses: [
        { id: "0", name: "在职" },
        { id: "1", name: "离职" },
        { id: "2", name: "其他" }
      ],
      addressOptions: [
        {
          value: "省份ID",
          label: "省份名称",
          children: [
            {
              value: "城市ID",
              label: "城市名称",
              children: [
                {
                  value: "县区ID",
                  label: "县区名称"
                }
                // 更多县区...
              ]
            }
            // 更多城市...
          ]
        }
        // 更多省份...
      ]
    };
  },
  methods: {
    submitForm() {
      let currentAddress = "";
      let optionLevel1 = this.addressOptions.find(
        option => option.value === this.form.currentAddress[0]
      );
      if (optionLevel1) {
        currentAddress += optionLevel1.label;
        if (optionLevel1.children) {
          let optionLevel2 = optionLevel1.children.find(
            option => option.value === this.form.currentAddress[1]
          );
          if (optionLevel2) {
            currentAddress += ", " + optionLevel2.label;
            if (optionLevel2.children) {
              let optionLevel3 = optionLevel2.children.find(
                option => option.value === this.form.currentAddress[2]
              );
              if (optionLevel3) {
                currentAddress += ", " + optionLevel3.label;
              }
            }
          }
        }
      }
      this.form.currentAddress = currentAddress;
      if (this.form.createTime) {
        this.form.createTime = this.$moment(this.form.createTime).format(
          "YYYY-MM-DD"
        );
      } else {
        this.form.createTime = "";
      }
      if (this.form.birthday) {
        this.form.birthday = this.$moment(this.form.birthday).format(
          "YYYY-MM-DD"
        );
      } else {
        this.form.birthday = "";
      }

      this.form.icon = this.imageUrl;
      console.log("员工信息: ", this.form);
      let employee = this.form;
      this.$axios.post("api/employee/updateEmployee", employee).then(res => {
        if (res.data.code == 200) {
          this.$message.success("修改成功!");
          this.$router.push({ path: "/employeeList" });
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    queryPost() {
      this.$axios.get("api/post/queryPost").then(res => {
        if (res.data.code == 200) {
          this.posts = res.data.data;
        }
      });
    },
    queryDepart() {
      this.$axios.get("api/depart/queryDepart").then(res => {
        if (res.data.code == 200) {
          this.departs = res.data.data;
        }
      });
    },
    queryNation() {
      this.$axios.get("api/nation/queryNation").then(res => {
        if (res.data.code == 200) {
          this.nations = res.data.data;
        }
      });
    },
    queryPolitical() {
      this.$axios.get("api/political/queryPolitical").then(res => {
        if (res.data.code == 200) {
          this.politicals = res.data.data;
        }
      });
    },
    getLocations() {
      this.$axios.get("api/location/queryLocation").then(response => {
        function removeChildrenForCounties(options) {
          for (const option of options) {
            if (option.children) {
              // 如果children是一个空数组，删除它
              if (option.children.length === 0) {
                delete option.children;
              }
              // 否则，递归处理下一级的选项
              else {
                removeChildrenForCounties(option.children);
              }
            }
          }
        }

        this.addressOptions = response.data.data;
        removeChildrenForCounties(this.addressOptions);

        this.queryById();
      });
    },
    handleAddressChange(value, selectedData) {
      this.form.currentAddress = value;
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.data;
    },
    queryById() {
      this.$axios.get("api/employee/queryById/" + this.id).then(res => {
        if (res.data.code == 200) {
          const originalForm = res.data.data;
          // 获取图片
          this.imageUrl = originalForm.icon;

          // 数字代码转为下拉列表的值
          const maritalstatus = this.maritalstatuses.find(
            item => item.id === String(originalForm.maritalstatus)
          );
          const status = this.statuses.find(
            item => item.id === String(originalForm.status)
          );
          const education = this.educations.find(
            item => item.id === String(originalForm.education)
          );
          originalForm.maritalstatus = maritalstatus ? maritalstatus.id : "";
          originalForm.status = status ? status.id : "";
          originalForm.education = education ? education.id : "";

          // 如果现住地址是字符串,转为数组
          // 如果currentAddress是字符串，转换为数组

          let labels = originalForm.currentAddress.split(", ");

          //然后使用findValueByLabel函数获取对应的值数组

          let values = this.findValueByLabel(this.addressOptions, labels);
          console.log(values);
          //最后将值数组赋值给form.currentAddress
          this.form = originalForm;
          this.form.currentAddress = values;
        }
      });
    },
    findValueByLabel(options, labels, index = 0) {
      const valuePath = [];

      function findInChildren(children, label) {
        let found = false;
        for (let child of children) {
          if (child.label === label) {
            valuePath.push(child.value);
            found = true;
            break;
          }
        }

        return found;
      }

      const currentLabel = labels[index];
      if (options.some(option => findInChildren([option], currentLabel))) {
        if (index < labels.length - 1) {
          let nextOptions = options.find(
            option => option.label === currentLabel
          ).children;
          let nextValues = this.findValueByLabel(
            nextOptions,
            labels,
            index + 1
          );
          if (nextValues) {
            valuePath.push(...nextValues);
          }
        }
        return valuePath;
      }
    },
    rollback() {
      this.$router.push({ path: "/employeeList" });
    }
  },

  created() {
    this.id = this.$route.query.id;
    this.queryDepart();
    this.queryPost();
    this.queryNation();
    this.queryPolitical();
    this.getLocations();
  }
};
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}
.el-row:last-child {
  margin-bottom: 0;
}
.avatar {
  width: 120px;
  /* 调整为你需要的宽度 */
  height: 120px;
  /* 调整为你需要的高度 */
  object-fit: cover;
  /* 这条语句会使图片以 "cover" 模式显示，保持图片的本身比例长宽比，裁剪超出部分 */
}
.el-input,
.el-select,
.el-cascader {
  width: 100% !important;
}
.el-button {
  border-radius: 20px;
  text-align: center; /* 文字居中  */
  border: none;
  color: white; /* 文字颜色白色  */
  cursor: pointer;
  display: inline-block;
  background: linear-gradient(
    to right,
    rgb(176, 119, 218),
    rgb(129, 214, 238)
  ); /* 渐变效果更换为浅紫色到浅蓝色 */
  transition-property: background-color, transform; /* 添加过渡属性 */
  transition-duration: 0.3s; /* 过渡持续时间 */
}
.el-button:hover {
  transform: scale(1.1); /* 按钮放大效果  */
  transition: transform 0.3s ease-in-out;
}
/* 图片边框动效 */
.avatar {
  border: 2px solid #ffffff;
  transition: border 0.5s ease-in-out;
}
.avatar:hover {
  border: 2px solid #12cbc4; /*鼠标悬停图片边框会变色*/
}

/* 输入框获取焦点时边框颜色变化 */
.el-input__inner:focus {
  border-color: #12cbc4;
}

/* 下拉框获取焦点时边框颜色变化 */
.el-select .el-input.is-focus .el-input__inner {
  border-color: #12cbc4;
}

/* 级联选择器获取焦点时边框颜色变化 */
.el-cascader .el-input.is-focus .el-input__inner {
  border-color: #12cbc4;
}
.container {
  position: relative;
  margin: 1rem;
  padding: 2.5rem;
  background: white;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  overflow: hidden;
  background: linear-gradient(60deg, #c4dcda 0%, #96e4e1 100%);
}
.form-required:before {
  content: "*";
  color: red;
}
</style>